package com.zgc.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;

import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.zgc.dto.OrderDto;
import com.zgc.entity.OrderDetail;
import com.zgc.entity.Orders;
import com.zgc.service.OrderDetailService;
import com.zgc.service.OrderService;
import com.zgc.util.AliPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Slf4j
@Controller
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private AliPayUtil aliPayUtil;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @GetMapping("/create")
    public void createPay(HttpServletResponse res, @RequestParam("id") Long id) throws AlipayApiException, IOException {
        System.out.println("用户支付");
//调用工具类，获取支付客户端
        AlipayClient alipayClient =aliPayUtil.getClent();
//根据订单id查询订单
        Orders orders=orderService.getById(id);
        //根据订单id查询订单详情
        QueryWrapper<OrderDetail> detailQueryWrapper=new QueryWrapper<>();
        detailQueryWrapper.lambda().eq(OrderDetail::getOrderId,orders.getId());
        List<OrderDetail> list=orderDetailService.list(detailQueryWrapper);
        OrderDto orderDto=new OrderDto();
//对象拷贝，把orders 数据放到orderDto
        BeanUtils.copyProperties(orders,orderDto);
//订单详情集合中的数据封装到Dto中
        orderDto.setOrderDetails(list);
        AlipayTradePagePayRequest request =aliPayUtil.getPayRequest(orderDto);
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        System.out.println(response.getBody());
        res.setContentType("text/html");
        res.setCharacterEncoding("utf8");
        res.getWriter().print(response.getBody());
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
    //确认支付结果 1 同步 get 2 异步 post 3. 主动校验
    @GetMapping("/check")
    public void check(@RequestParam("out_trade_no") Long id,HttpServletResponse
            response) throws IOException {
//修改订单状态，变成已支付
        Orders orders=new Orders();
        orders.setId(id);
        orders.setStatus(2); //2已支付
        orderService.updateById(orders);
//重定向
        response.sendRedirect("/front/page/pay-success.html");
    }
}